function showSuccessUI(msg){
	alert(msg);
}
function showDangerUI(msg){
	alert(msg);
}


function getObjectURL(file) {
	var url;
	if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
		file.select();
		url = document.selection.createRange().text;
	} else{
		url = window.URL.createObjectURL(file);
	}
	return url;
};

function getDuration(file,callback){
	var url = getObjectURL(file);
	var video = document.createElement("VIDEO");
	video.src = url;
	$("body").append(video);
	$(video).hide(0);
	var t = setInterval(function(){
		if(video.duration > 0){
			//获取到视频时长，关闭定时器
			clearInterval(t);
			//修改input的值
			callback(Math.ceil(video.duration));
			//溢出元素
			$(video).remove();
		}
	},100);
}

//获取文件上传的路径
function getPath(hash,fileName,path){
	var timestamp = Date.parse(new Date());
	timestamp = timestamp / 1000;
	var date = new Date();
	//获取后缀名
	var suffix=fileName.match(/\.(\w+)$/);
	suffix = suffix[0];

	return path+hash+suffix;
}

//获取文件的hash值
function fileMd5(file,callback){
	var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
	var chunkSize = 2097152; //读取时分割文件 按每一块2MB分割
	var chunks = Math.ceil(file.size / chunkSize);
	var currentChunk = 0;
	var spark = new SparkMD5.ArrayBuffer();

	function loadNext() {
		var fileReader = new FileReader();
		fileReader.onload = function(e){
			spark.append(e.target.result); // 追加数组缓冲区
			currentChunk++;
			if (currentChunk < chunks){
				loadNext();
			}else{
				callback(spark.end());
			}
		};
		fileReader.onerror = function () {
			showDangerUI("计算文件MD5出现问题");
		};
		var start = currentChunk * chunkSize,
			end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
		fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
	};
	loadNext();
}

$(function (){

  //图片预览
  var i = 1;
  function imgPreview(file, $input){
    try{
      if(!window.FileReader){
        $input.get(0).select();
        var reallocalpath = document.selection.createRange().text;
        var img = getShowImg();
        $(img).css("filter","progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")")
        $(img).attr("src",'');
       }else{
        var reader = new FileReader();
        reader.readAsDataURL(file[0]);
         reader.onload = function(e){
        	 var img = getShowImg();
        	 $(img).attr("src",this.result);
         }
       }
    }catch(ex){
      var fileSrc = $input.val(),
        fileName = fileSrc.substring(fileSrc.lastIndexOf('\\')+1);
        if($('#errMsg').html() == ''){$('#errMsg').html('当前浏览器不支持图片预览');}
      $('<div>').addClass('filePItem').append($input)
      .append($('<span>').html(fileName)).append($('<i>'))
      .appendTo('#output');
    }
  }

  function getShowImg(){
	  var $img = $('#output').find("img").eq(0);
	  if($img.length == 0){
		  $img = $('<img>'), $div = $('<div>'), $i = $('<i>');
	      $img.width(90).height(90);
	      $div.attr('id', 'file' + i++).addClass('fileItem');
	      $div.append($img).append($i);
	      $('#output').append($div);
	  }
	  return $img;
  }

  $('#addpic').on('change', function(){
      var $input = $(this).find('input');
      var files = $input.get(0).files?$input.get(0).files:$input;
      imgPreview(files, $input);
      
  });

  //删除图片
  $('#output').on('click', 'i', function(){
    $(this).parent().remove();
    if($("#output").find(".fileItem").length<=5){
        $("#addpic").show();
      }
  });
    
});